package com.framework.core.interceptor;

import com.framework.core.constant.Globals;
import com.framework.core.domain.SessionVo;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

public class CommonInterceptor extends HandlerInterceptorAdapter {

    static Logger logger = Logger.getLogger(CommonInterceptor.class);

    private List<String> allowUrls;

    public void setAllowUrls(List<String> allowUrls) {
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String requestUri = request.getRequestURI();
        if(requestUri.equals("/")) {
            return true;
        }
        for (String url : allowUrls) {
            if (requestUri.contains(url)) {
                return true;
            }
        }

        HttpSession session = request.getSession();
        SessionVo user = (SessionVo) session.getAttribute(Globals.USER_SESSION);
        if (null == user) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            StringBuilder builder = new StringBuilder();
            builder.append("<script type=\"text/javascript\" charset=\"utf-8\">");
            //builder.append("alert(\"页面过期，请重新登录！\");");
            builder.append("window.top.location.href=\"");
            builder.append("/\";</script>");
            out.print(builder.toString());
            out.close();
            return false;
        }
        return true;
    }

}
